<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="30%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="权限字符" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from "element-plus";

const props = defineProps({
  id: {
    type: String,
    default: "",
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogFormVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const form = ref({
  id: "",
  name: "",
  code: "",
  remark: "",
});

const rules = ref({
  name: [{ required: true, message: "请输入角色名称" }],
  code: [{ required: true, message: "请输入权限字符" }],
});

const formRef = ref(null);

//初始化后台提供的表单数据
const initFormData = async (id) => {
  const res = await requestUtil.get("role/" + id);
  form.value = res.data.sysRole;
};

const emits = defineEmits(["update:modelValue", "initDate"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post("role/save", form.value);
      if (res.code == 20000) {
        ElMessage.success("执行成功！");
        formRef.value.resetFields();
        //调用主页面刷新分页查询 数据实时性
        emits("initDate");
        handleClose();
      } else {
        ElMessage.error(data.message);
      }
    } else {
      console.log("fail");
    }
  });
};

//监听props 实现表单数据的实时刷新(修改 还是 新增)
watch(
  () => props.dialogFormVisible,
  () => {
    let id = props.id;
    if (id != "") {
      initFormData(id);
    } else {
      console.log("hhh");
      form.value = {
        id: "",
        name: "",
        code: "",
        remark: "",
      };
    }
  }
);
</script>

<style lang="scss" scoped>
</style>
